﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using HZU.ZP.Domain.IService;
using HZU.ZP.Domain.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace HZU.ZP.Controllers
{
    public class CompanyInformationController : Controller
    {
        private static int companyId;
        private ICompanyService _companyService;
        private ICompanyInformationService _companyInformationService;
        private ICompayPictureService _compayPictureService;
        private IHostingEnvironment _hostingEnv;
        public CompanyInformationController(ICompanyInformationService companyInformationService,
            IHostingEnvironment hostingEnv, ICompanyService companyService, ICompayPictureService compayPictureService)
        {
            _companyInformationService = companyInformationService;
            _companyService = companyService;
            _compayPictureService = compayPictureService;
            _hostingEnv = hostingEnv;
        }

        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }

        [Authorize]
        [HttpGet]
        // GET: /<controller>/
        public IActionResult GetCompanyInformation(string email)
        {
            CompanyInformationView companyInformationView = new CompanyInformationView();
            var company = _companyService.GetByEmail(email);
            companyId = company.Id.Value;
            companyInformationView.CompanyInformation = _companyInformationService.Get(companyId);
            companyInformationView.CompayPictures = _compayPictureService.GetByCompanyId(companyId);

            ViewData["Title"] = "企业基本信息";
            return View(companyInformationView);
        }

        [Authorize(Roles ="Company")]
        [HttpPost]
        public IActionResult Save([FromBody]CompanyInformation companyInformation)
        {
           _companyInformationService.Update(companyInformation);
            return Json(AjaxResult.ReturnMessage(1, "保存成功"));
        }

        [Authorize(Roles ="Company")]
        [HttpPost]
        public IActionResult DeleteImg(int id)
        {
            _compayPictureService.Delete(id);
            return Json(AjaxResult.ReturnMessage(1, "删除成功"));
        }

        [Authorize]
        [HttpGet]
        public IActionResult GetCompanyInformationA(int companyId)
        {
            CompanyInformationView companyInformationView = new CompanyInformationView();
            companyInformationView.CompanyInformation = _companyInformationService.Get(companyId);
            companyInformationView.CompayPictures = _compayPictureService.GetByCompanyId(companyId);

            ViewData["Title"] = "企业基本信息";
            return View(companyInformationView);
        }

        [Authorize(Roles ="Company")]
        [HttpPost]
        public ActionResult UploadImg(IFormFileCollection files)
        {            
            CompayPicture compayPicture = new CompayPicture();
            if (_compayPictureService.GetByCompanyId(companyId).Count() >= 4)
            {
                return Json(AjaxResult.ReturnMessage(0, "最多只能上传4张图片"));
            }
            if (files.Count != 1)
            {
                return Json(AjaxResult.ReturnMessage(0, "上传失败，无数据"));
            }
            //返回的文件地址
            List<string> filenames = new List<string>();
            var now = DateTime.Now;
            //文件存储路径
            var filePath = string.Format("/CompayPictures/{0}/{1}/{2}/", now.ToString("yyyy"), now.ToString("yyyyMM"), now.ToString("yyyyMMdd"));
            //获取当前web目录
            var webRootPath = _hostingEnv.WebRootPath;
            if (!Directory.Exists(webRootPath + filePath))
            {
                Directory.CreateDirectory(webRootPath + filePath);
            }
            try
            {
                foreach (var item in files)
                {
                    if (item != null)
                    {
                        #region  图片文件的条件判断
                        //文件后缀
                        var fileExtension = Path.GetExtension(item.FileName);

                        //判断后缀是否是图片
                        const string fileFilt = ".gif|.jpg|.jpeg|.png";
                        if (fileExtension == null)
                        {
                            return Json(AjaxResult.ReturnMessage(0, "上传失败，该文件不是.gif|.jpg|.jpeg|.png格式"));
                        }
                        if (fileFilt.IndexOf(fileExtension.ToLower(), StringComparison.Ordinal) <= -1)
                        {
                            return Json(AjaxResult.ReturnMessage(0, "上传失败，该文件不是.gif|.jpg|.jpeg|.png格式"));
                        }

                        //判断文件大小    
                        long length = item.Length;
                        if (length > 1024 * 1024 * 2) //2M
                        {
                            return Json(AjaxResult.ReturnMessage(0, "上传失败，图片不能大于2M"));
                        }

                        #endregion

                        var strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得时间字符串
                        var strRan = Convert.ToString(new Random().Next(100, 999)); //生成三位随机数
                        var saveName = strDateTime + strRan + fileExtension;

                        //插入图片数据                 
                        using (FileStream fs = System.IO.File.Create(webRootPath + filePath + saveName))
                        {
                            item.CopyTo(fs);
                            fs.Flush();
                        }
                        filenames.Add(filePath + saveName);
                        compayPicture.CompanyId = companyId;
                        compayPicture.Picture = filePath + saveName;
                        _compayPictureService.Add(compayPicture);
                    }
                }
                return Json(AjaxResult.ReturnMessage(1, "上传成功", compayPicture));
            }
            catch (Exception ex)
            {
                return Json(AjaxResult.ReturnMessage(0, ex.Message));
            }
        }
    }
}
